package bowling;

import java.util.ArrayList;

public class GameImpl implements Game {

	private int totalScore = 0;
	private int throwNum = 0;
	private int frameScore = 0;
	ArrayList<Integer> bowlingThrows;
	private boolean firstThrow;

	public GameImpl() {
		bowlingThrows = new ArrayList<Integer>();
		firstThrow = false;
	}

	@Override
	public void throwBall(int pins) {
		bowlingThrows.add(pins);
	}

	public void scoringLogic(int pins) {

		toggleFirstThrow();

		if (endOfFrame()) {
			frameScore = 0;
		}

		throwNum = throwNum + 1;
		totalScore = totalScore + pins;
		frameScore += pins;

		if (validStrike()) {
			totalScore += bowlingThrows.get(throwNum);
			totalScore += bowlingThrows.get(throwNum + 1);
			frameScore = 0;
			toggleFirstThrow();
		}
		
		if (!firstThrow) {
			if (validSpare()) {
				totalScore += bowlingThrows.get(throwNum);
				frameScore = 0;
			}
		}
	}

	private void toggleFirstThrow() {
		firstThrow = firstThrow ? false : true;
	}

	private boolean validStrike() {
		return firstThrow && frameScore == 10 && throwNum < bowlingThrows.size() - 2;
	}

	private boolean validSpare() {
		return frameScore == 10 && throwNum < bowlingThrows.size() - 1;
	}

	private boolean endOfFrame() {
		return throwNum > 1 && throwNum % 2 == 0 || frameScore == 10;
	}

	@Override
	public int score() {
		for (Integer pins : bowlingThrows) {
			scoringLogic(pins);
		}

		return totalScore;
	}

}
